package com.pisces.tool.query;


import java.io.Serializable;
import java.util.*;

public class QueryObject implements Serializable {

	private static final long serialVersionUID = 1;

	public static final int SORT_ASC = 1;
	public static final int SORT_DESC = 2;

	private int pageNumber = 1;	//页码

	private int pageSize = 20;	//每页几条

	private Map<String, Object> queryParam;

	private LinkedHashMap<String,Integer> sort;

	public QueryObject(int pageNumber, int pageSize) {
		this.queryParam = new HashMap<>();
		this.sort = new LinkedHashMap<String,Integer>();
		this.pageNumber = pageNumber;
		this.pageSize = pageSize;
	}

	public QueryObject() {
		this.queryParam = new HashMap();
		this.sort = new LinkedHashMap<String,Integer>();
	}

	public QueryObject addQuery(String name, Object value) {
		queryParam.put(name, value);
		return this;
	}

	public <T> T getQuery(String name) {
		return (T)queryParam.get(name);
	}

	public QueryObject removeQuery(String column) {
		queryParam.remove(column);
		return this;
	}

	public QueryObject addSort(String name, int sortType) {
		sort.put(name, sortType);
		return this;
	}

	public QueryObject removeSort(String name) {
		sort.remove(name);
		return this;
	}

	public LinkedHashMap<String, Integer> getSort() {
		return sort;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public String getSortString() {
        Set<String> columns = sort.keySet();
        if (columns.size() == 0) {
            return "";
        }
        StringBuilder sortString = new StringBuilder(" ORDER BY");
        Iterator<String> names = columns.iterator();
        while (names.hasNext()) {
            String name = names.next();
            sortString.append(" `").append(name).append("` ");
            if (sort.get(name) == QueryObject.SORT_ASC) {
                sortString.append("ASC,");
            } else {
                sortString.append("DESC,");
            }
        }
        return sortString.substring(0, sortString.length() - 1);
    }
}
